/*
 * The MIT License
 *
 * Copyright 2011 Edwin Bratini <edwin.bratini@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/*
 * CambiarEstadoRefermiento.java
 *
 * Created on Dec 12, 2011, 12:02:39 PM
 */
package org.salvador_dali.psychsys.ui;

import java.awt.Frame;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import org.salvador_dali.psychsys.business.jpa_controllers.ReferimientoJpaDao;
import org.salvador_dali.psychsys.model.entities.Referimiento;

/**
 *
 * @author Edwin Bratini <edwin.bratini@gmail.com>
 */
public class CambiarEstadoRefermiento extends javax.swing.JDialog {
    private Referimiento referimiento;
    private ReferimientoJpaDao jpaRefDao;

    /** Creates new form CambiarEstadoRefermiento */
    public CambiarEstadoRefermiento(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        getRootPane().setDefaultButton(btnOk);
    }

    public CambiarEstadoRefermiento(Referimiento referimiento, ReferimientoJpaDao jpaRefDao, Frame owner, boolean modal) {
        this(owner, modal);
        this.referimiento = referimiento;
        this.jpaRefDao = jpaRefDao;
    }

    public JComboBox getCmbEstadoReferimiento() {
        return cmbEstadoReferimiento;
    }

    public void setCmbEstadoReferimiento(JComboBox cmbEstadoReferimiento) {
        this.cmbEstadoReferimiento = cmbEstadoReferimiento;
    }

    public ReferimientoJpaDao getJpaRefDao() {
        return jpaRefDao;
    }

    public void setJpaRefDao(ReferimientoJpaDao jpaRefDao) {
        this.jpaRefDao = jpaRefDao;
    }

    public Referimiento getReferimiento() {
        return referimiento;
    }

    public void setReferimiento(Referimiento referimiento) {
        this.referimiento = referimiento;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlEstadoReferimiento = new javax.swing.JPanel();
        cmbEstadoReferimiento = new javax.swing.JComboBox();
        btnOk = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cambiar Estado Referimiento");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        pnlEstadoReferimiento.setBorder(javax.swing.BorderFactory.createTitledBorder("Estado Referimiento"));

        cmbEstadoReferimiento.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Abierto", "Cerrado", "Pendiente" }));

        javax.swing.GroupLayout pnlEstadoReferimientoLayout = new javax.swing.GroupLayout(pnlEstadoReferimiento);
        pnlEstadoReferimiento.setLayout(pnlEstadoReferimientoLayout);
        pnlEstadoReferimientoLayout.setHorizontalGroup(
            pnlEstadoReferimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlEstadoReferimientoLayout.createSequentialGroup()
                .addComponent(cmbEstadoReferimiento, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pnlEstadoReferimientoLayout.setVerticalGroup(
            pnlEstadoReferimientoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlEstadoReferimientoLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(cmbEstadoReferimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        btnOk.setText("Ok");
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnlEstadoReferimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(btnOk, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnOk)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnCancelar))
                    .addComponent(pnlEstadoReferimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed
        // TODO add your handling code here:
        try {
            if (referimiento != null) {
                if (referimiento.getRefEstadoReferimiento() == cmbEstadoReferimiento.getSelectedItem().toString().charAt(0)) {
                    this.dispose();
                    return;
                }
                referimiento.setRefEstadoReferimiento(cmbEstadoReferimiento.getSelectedItem().toString().charAt(0));
                jpaRefDao.update(referimiento);
                
                JOptionPane.showMessageDialog(this, "El estado de referimiento ha sido editado exitosamente", "Referimiento", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            } else {
                throw  new Exception("El referimiento no esta establecido");
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Error al cambiar estado del referimiento.\n" + e.getMessage(), "Referimiento", JOptionPane.ERROR_MESSAGE);
            return;
        }
    }//GEN-LAST:event_btnOkActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        if (referimiento != null) {
            char chrEstado = referimiento.getRefEstadoReferimiento();
            String estado = (chrEstado == 'A' ? "Abierto" : (chrEstado == 'C' ? "Cerrado" : "Pendiente"));
            cmbEstadoReferimiento.setSelectedItem(estado);
        }
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CambiarEstadoRefermiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CambiarEstadoRefermiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CambiarEstadoRefermiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CambiarEstadoRefermiento.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                CambiarEstadoRefermiento dialog = new CambiarEstadoRefermiento(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnOk;
    private javax.swing.JComboBox cmbEstadoReferimiento;
    private javax.swing.JPanel pnlEstadoReferimiento;
    // End of variables declaration//GEN-END:variables
}
